import { getToken, removeToken, setToken } from '@/utils/auth'
import { getInfoApi, getUserInfoDetailApi, login } from '@/api/user'
import { resetRouter } from '@/router'

const state = {
  token: getToken(),
  userInfo: {}
}
const mutations = {
  handleLogin(state, newToken) {
    state.token = newToken
    setToken(newToken)
  },
  getUserInfo(state, payload) {
    state.userInfo = payload
  },
  removeToke(state) {
    removeToken()
    state.token = null
  },
  removeUserInfor(state) {
    state.userInfo = {}
  }
}
const actions = {
  async handleAction(context, data) {
    const res = await login(data)
    // context.commit('handleLogin', res.data.data)
    context.commit('handleLogin', res)
  },
  async getUserInfoAction(context) {
    const res = await getInfoApi()
    // 用户的基本资料,里面有用户ID，但是没有头像，根据ID调用第二个接口去获取头像及其他数据
    const userInfoDetail = await getUserInfoDetailApi(res.userId)
    // context.commit('getUserInfo', res)，与ID获取的信息进行拼接
    context.commit('getUserInfo', { ...res, ...userInfoDetail })
    return { ...res, ...userInfoDetail }
  },
  // 退出登录，触发mutations
  layoutAction(context) {
    context.commit('removeToke')
    context.commit('removeUserInfor')
    resetRouter()
    context.commit('permission/setRoutes', [], { root: true })
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}

